package com.yuwenxin.servlet.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class decodeFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("filter initial...");
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("decodeFilter is doing...");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        request.setCharacterEncoding("utf-8");
        response.setContentType("Text/html;charset=utf-8");

        CharacterRequest characterRequest = new CharacterRequest(request);
        filterChain.doFilter(characterRequest, response);
    }

    public void destroy() {
        System.out.println("filter destroy...");
    }
}

class CharacterRequest extends HttpServletRequestWrapper{

    private HttpServletRequest request;

    public CharacterRequest(HttpServletRequest request) {
        super(request);
        this.request = request;
    }

    public String getParameter(String name){
        String value = super.getParameter(name);
        if (value == null){
            return null;
        }

        String method = super.getMethod();
        if ("get".equalsIgnoreCase(method)){
            try {
                value = new String(value.getBytes("iso-8859-1"), "utf-8");
            }catch (UnsupportedEncodingException e){
                throw new RuntimeException(e);
            }
        }
        return value;
    }

    @Override
    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }
}